package com.wzy.netty.core.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.net.URI;
import java.nio.charset.StandardCharsets;

/**
 * 描述  : ChannelInboundHandlerAdapter(父类)  SimpleChannelInboundHandler(子类)
 * 创建人:    Wzy
 * 创建时间: 2020-06-11  13:25
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    //接受保护数据的方法
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject o) throws Exception {
        if (o instanceof HttpRequest) {
            System.out.println("msg类型=" + o.getClass());
            System.out.println("客户端地址" + channelHandlerContext.channel().remoteAddress());
            HttpRequest httpRequest = (HttpRequest) o;
            URI uri = new URI(httpRequest.uri());
            //  System.out.println(uri);
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("请求了favicon");
                return;
            }
        }

        /*返回给客户端消息,满足http协议要求,需要封装一下*/
        ByteBuf content = Unpooled.copiedBuffer("hello,我是服务器", StandardCharsets.UTF_16);
        //构造http响应,指定 协议版本 和 状态码
        DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
        httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain,charset=utf-8");
        httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

        /*将构造好的响应体返回*/
        channelHandlerContext.writeAndFlush(httpResponse);

    }
}
